from django.shortcuts import render, redirect, HttpResponse
from administrative.models import Company, User, Topicsattachments
from payment_management.models import *
from django.views import View
import json, uuid, datetime, os
from logistics.MessagePushOperationRecords import RecordAndPush
from personal_center.models import MakeCopy


class OvertimeAllowanceListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'payment_management/OvertimeAllowanceList.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.supportsubsidies_set.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"), 'start_time': obj.start_time, 'end_time': obj.end_time, 'note': obj.note,
                      'status': obj.get_state_str(), 'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='OvertimeAllowanceDraft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='OvertimeAllowanceDetail.html?id={obj.id}'>查看</a> | <a href='OvertimeAllowanceDetail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state not in ['draft', 'stop']
                      else f"<a href='OvertimeAllowanceDetail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='OvertimeAllowanceDetail.html?id={obj.id}'>查看</a>",
                      } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class OvertimeAllowanceIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'payment_management/OvertimeAllowanceIndex.html', {'realname': real_name, 'position': position, 'department': department, "uuid": uuid.uuid4()})

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        start_time = request.POST.get("start_time", "")
        end_time = request.POST.get("end_time", "")
        note = request.POST.get("note", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "体检科支援加班补助")
        except:
            pass

        if flow_id:
            obj = SupportSubsidies.objects.get(id=int(flow_id))
            obj.start_time = start_time
            obj.end_time = end_time
            obj.note = note
            obj.save()
            obj.current_audit_users.clear()
            obj.supportsubsidiesrecord_set.filter(state='unaudit').delete()
            message_str = "修改成功"
        else:
            obj = SupportSubsidies.objects.create(apply_user=request.user, company=request.user.company, start_time=start_time, fj_number=fj_number, end_time=end_time, note=note)
            message_str = "创建成功"

        flag = True
        one_step = request.user.company.head_people
        if request.user != one_step:
            SupportSubsidiesRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=obj)
            obj.state = 'one'
            obj.current_audit_users.add(one_step)
            flag = False

        two_setp = request.user.company.leaders_id
        SupportSubsidiesRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=obj)
        if flag:
            obj.state = 'two'
            obj.current_audit_users.add(two_setp)

        three_setp = Company.objects.get(id=23).leaders_id
        SupportSubsidiesRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=obj)

        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class OvertimeAllowanceDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = SupportSubsidies.objects.get(id=flow_id)

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "file_list": file_list}
        return render(request, 'payment_management/OvertimeAllowanceDraft.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        start_time = request.POST.get("start_time", "")
        end_time = request.POST.get("end_time", "")
        note = request.POST.get("note", "")

        if flow_id:
            obj = SupportSubsidies.objects.get(id=int(flow_id))
            obj.start_time = start_time
            obj.end_time = end_time
            obj.note = note
            obj.save()
            message_str = "修改成功"
        else:
            obj = SupportSubsidies.objects.create(apply_user=request.user, company=request.user.company, start_time=start_time, fj_number=fj_number, end_time=end_time, note=note)
            message_str = "创建成功"
        obj.state = 'draft'
        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class OvertimeAllowanceDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = SupportSubsidies.objects.get(id=flow_id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.supportsubsidiesrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.supportsubsidiesrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                     'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false',
                   'flow_dict': flow_dict, "revise": revise,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three'] and request.user == obj.apply_user else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'payment_management/OvertimeAllowanceDetail.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "体检科支援加班补助")
        except:
            pass
        obj = SupportSubsidies.objects.get(id=int(flow_id))

        if not obj.supportsubsidiesrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnData = {'code': 400, 'message': '该流程已审核，请勿重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.supportsubsidiesrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.supportsubsidiesrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.supportsubsidiesrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.supportsubsidiesrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.supportsubsidiesrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                obj_state = 'end'
                MakeCopy.objects.create(recipient=Company.objects.get(id=10).head_people, process_id=obj.id, type='q')
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "体检科支援加班补助"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = '体检科支援加班补助'
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class OvertimeAllowanceStopView(View):
    def post(self, request):
        flow_id = request.POST.get('id', '')
        types = request.POST.get('types', '')
        obj = SupportSubsidies.objects.get(id=int(flow_id))
        if obj.state == 'end':
            returnData = {'code': 500, 'message': '操作失败，已完结流程无法操作！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_users.clear()
        if types == 'stop':
            obj.state = 'stop'
            obj.save()
            returnData = {'code': 200, 'message': '终止成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            obj.supportsubsidiesrecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")